package com.gzhryc.net_marketing.cloud.business.event;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.RandomUtils;

import com.gzhryc.common.event.AbsDelayHandler;
import com.gzhryc.common.event.DelayHandleService;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.net_marketing.cloud.business.dao.db.PayGoodsOrder;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApply;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApplyMember;
import com.gzhryc.net_marketing.cloud.business.dao.enums.PayGoodsOrderLogEnum;
import com.gzhryc.net_marketing.cloud.business.dao.enums.TeamPayApplyMemberEnum;
import com.gzhryc.net_marketing.cloud.business.services.PayGoodsOrderService;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyMemberService;
import com.gzhryc.net_marketing.cloud.business.services.TeamPayApplyService;
import com.gzhryc.net_marketing.cloud.business.services.models.PayGoodsOrderLogItem;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;

public class TeamPayApplySettlementEventHandler extends AbsDelayHandler<TeamPayApplySettlementEvent> {

	static Logger log = Logger.getLogger(TeamPayApplySettlementEventHandler.class);

	private OperateInfo operateInfo;

	public TeamPayApplySettlementEventHandler(OperateInfo operateInfo){
		this.operateInfo = operateInfo;
	}

	@Override
	public boolean execute(TeamPayApplySettlementEvent event) {
			try {
				TeamPayApply apply = event.getApply();
				if (apply != null) {
					if(TeamPayApplyService.self().toStartSettlement(apply.getId())) {
						try {
							List<TeamPayApplyMember> memberList = TeamPayApplyMemberService.self().findByApplyIdAndState(apply.getId(),
									TeamPayApplyMemberEnum.State.Participating.index());
							if (memberList != null && memberList.size() > 0 && memberList.size() >= apply.getTeamMemberCount()) {
								int money = setRewardMoney(apply,memberList);
								log.info("团拼奖励计算完成，预计奖励金额：{{0}}，实际奖励金额：{{1}}",apply.getRewardMoney(),money);

								int surplusMoney = money - apply.getRewardMoney();
								if(surplusMoney <= 0){
									
									if (TeamPayApplyService.self().settlement(apply, memberList, operateInfo)) {
										for (TeamPayApplyMember member : memberList) {
											PayGoodsOrder payOrder = PayGoodsOrderService.self().getByTradeNo(member.getBusinessTradeNo());
											if(payOrder != null) {
												PayGoodsOrderLogItem logsItem = new PayGoodsOrderLogItem();
												logsItem.setContent(event.getApply().getId() + "团拼结算成功购买商品");
												logsItem.setProgramType(operateInfo.getProgramType());
												logsItem.setOperatorType(EOperatorType.System.index());
												logsItem.setOperator("团拼结算事件处理程序");
												logsItem.setState(PayGoodsOrderLogEnum.ItemState.Success.index());
												logsItem.setCreateDate(new Date());
												PayOrderLogEvent logEvent = new PayOrderLogEvent(payOrder.getTradeNo()
														, payOrder.getCreateDate(), logsItem);
												DelayHandleService.get().addEvent(logEvent);
											}
										}
									}else{
										log.error("团拼结算失败，事件信息：{{0:json}}", event);
									}
								}else{
									log.error("奖励金额计算超界，团拼结算失败，事件信息：{{0:json}}", event);
								}
							}else {
								log.error("团拼结算失败,团拼人数不足结算条件，事件信息：{{0:json}}", event);
							}
						}finally{
							TeamPayApplyService.self().toWaitSettlement(apply.getId());
						}
					}
				}
			}catch (Exception e){
				log.error(e.getMessage(),e);
			}finally{
				JdbcSession.clear();
			}
		return true;
	}

	public static int setRewardMoney(TeamPayApply apply, List<TeamPayApplyMember> memberList){
		//奖励金额计算
		int rewardMoney = apply.getRewardMoney() / 3;
		int money = 0;
		for (int i=0;i<memberList.size();i++) {
			TeamPayApplyMember member = memberList.get(i);
			int tempMoney = RandomUtils.nextInt(0,rewardMoney);
			if(tempMoney == 0){tempMoney = 1;}		//最少1分钱
			int tempTotalMoney = money + tempMoney;
			if(tempTotalMoney > apply.getRewardMoney()){
				int surplusCount = memberList.size() - i;		//还剩多少人
				int surplusMoney = apply.getRewardMoney() - money;	//还剩多少钱
				tempMoney = surplusMoney / surplusCount + 1;
				money = money + tempMoney;
				member.setRewardMoney(tempMoney);
			}else{
				money = money + tempMoney;
				member.setRewardMoney(tempMoney);
			}
		}

		int surplusMoney = money - apply.getRewardMoney();
		if(surplusMoney < 0){
			log.info("随机剩余：{{0}}",surplusMoney);
			//如果有剩余就平均分
			int tempMoney = Math.abs(surplusMoney) / memberList.size();
			if(tempMoney > 0) {
				for (TeamPayApplyMember member : memberList) {
					member.setRewardMoney(member.getRewardMoney() + tempMoney);
					money = money + tempMoney;
				}
			}
			surplusMoney = money - apply.getRewardMoney();
			if(surplusMoney < 0){
				memberList.get(0).setRewardMoney(memberList.get(0).getRewardMoney() + Math.abs(surplusMoney));
				money = money + surplusMoney;
			}
		}else if(surplusMoney > 0){
			log.info("随机超出：{{0}}",surplusMoney);
			//如果超出就平均减
			int tempMoney = surplusMoney / memberList.size();
			if(tempMoney > 0) {
				for (TeamPayApplyMember member : memberList) {
					if(member.getRewardMoney() > tempMoney) {
						member.setRewardMoney(member.getRewardMoney() - tempMoney);
						money = money - tempMoney;
					}
				}
			}
			surplusMoney = money - apply.getRewardMoney();
			if(surplusMoney > 0){
				//减少最高奖励
				int index = -1;
				int maxMoney = 0;
				for (int i=0;i<memberList.size();i++) {
					TeamPayApplyMember member = memberList.get(i);
					if(maxMoney < member.getRewardMoney()){
						index = i;
						maxMoney = member.getRewardMoney();
					}
				}
				memberList.get(index).setRewardMoney(memberList.get(index).getRewardMoney() - surplusMoney);
				money = money - surplusMoney;
			}
		}

		return money;
	}
}
